package Main.tcp;

import Main.pojo.TcpMessage;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * PACKAGE_NAME: Main.tcp
 * Description:
 */
public class TCPTest1 {

    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner scanner = new Scanner(System.in);
        new Thread(new TCPServer()).start();
        System.out.println("等待0.3秒！");
        Thread.sleep(300);
        System.out.println("开始连接服务器！");
        Socket socket = new Socket("localhost", 8888);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        while (true) {
            TcpMessage strMsg = new TcpMessage();
            System.out.println("请输入信息:");
            strMsg.msg = scanner.next();
            objectOutputStream.writeObject(strMsg);
            objectOutputStream.flush();
        }
    }
}


class TCPServer implements Runnable {
    private ServerSocket serverSocket;

    TCPServer() throws IOException {
        serverSocket = new ServerSocket(8888);
        serverSocket.setSoTimeout(60 * 1000);
        System.out.println("启动服务器成功！");
    }

    @Override
    public void run() {
        try {
            Socket socket = serverSocket.accept();
            System.out.println("收到连接！");
            ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            while (true) {
                TcpMessage tcpMessage = (TcpMessage) objectInputStream.readObject();
                System.out.println(tcpMessage);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
